<template>
  <template v-if="cacheListLength">
    <div v-if="fixed" class="ant-pro-multi-tab-fixed" />
    <a-tabs
      type="editable-card"
      v-bind="$attrs"
      :active-key="activeKey"
      :style="{
        margin: 0,
        paddingTop: '6px',
        width: sideWidth
      }"
      hide-add
      :class="{ 'ant-pro-multi-tab-wrap': true, 'ant-pro-multi-tab-wrap-fixed': fixed }"
      @change="handleActiveKeyChange"
    >
      <template #rightExtra>
        <a-dropdown placement="bottomRight">
          <ellipsis-outlined :rotate="90" class="ant-dropdown-link ant-pro-multi-tab-dropdown-menu-btn" />
          <template #overlay>
            <a-menu>
              <a-menu-item key="close-other" :disabled="cacheListLength === 1" @click="closeOther(route.path)">关闭其他</a-menu-item>
              <a-menu-item key="refresh" @click="handleReloadPage()">刷新当前页</a-menu-item>
            </a-menu>
          </template>
        </a-dropdown>
        <span style="cursor: pointer; font-size: 16px; margin-right: 10px">
          <AvicIcon v-if="store.fullScreen" svg="avic-fullscreen-exit-fill" title="退出全屏" @click="exitFullScreen" />
          <AvicIcon v-else svg="avic-fullscreen-fill" title="全屏" @click="fullScreen" />
        </span>
      </template>
      <a-tab-pane v-for="(item, index) in store.cacheList" :key="item.route.path" class="contextmenu-wrap" :closable="false">
        <template #tab>
          <dashbord-dropdown v-if="item.tabTitle == '首页'" ref="tabsDropRefName" :tab-info="item" />
          <a-dropdown v-if="item.tabTitle != '首页'" :trigger="['contextmenu']">
            <span class="ant-pro-multi-tab-title">
              <span class="ant-pro-multi-tab-title-text">{{ item.tabTitle ? t(`${item.tabTitle}`) : t(`${item.route.meta.title}`) }}</span>
              <reload-outlined
                v-if="store.current === item.route.path"
                class="ant-pro-multi-tab-reload-btn"
                :spin="spin"
                @click="handleReloadPage(item.route.path)"
              />
              <close-outlined
                v-if="cacheListLength > 1 && !item.lock"
                class="ant-pro-multi-tab-close-btn"
                @click="(e) => handleClose(e, item.route.path)"
              />
            </span>
            <template #overlay>
              <a-menu>
                <a-menu-item key="close-other" :disabled="cacheListLength === 1" @click="closeOther(item.route.path)">关闭其他</a-menu-item>
                <a-menu-item key="close-left" :disabled="index === 0" @click="closeLeft(item.route.path)">关闭左侧标签</a-menu-item>
                <a-menu-item key="close-right" :disabled="index + 1 === cacheListLength" @click="closeRight(item.route.path)">
                  关闭右侧标签
                </a-menu-item>
                <a-menu-item @click="handleReloadPage(item.route.path)">刷新当前页</a-menu-item>
              </a-menu>
            </template>
          </a-dropdown>
        </template>
      </a-tab-pane>
    </a-tabs>
  </template>
</template>

<script lang="ts">
/* eslint-disable function-paren-newline */
import { defineComponent, ref, computed, inject } from 'vue';
import { ReloadOutlined, EllipsisOutlined, CloseOutlined } from '@ant-design/icons-vue';
// import DashbordDropdown from './dashbord-dropdown/index_top.vue';
import { useI18n } from 'vue-i18n';
import { injectMultiTabStore, useMultiTab } from './multi-tab-store';
import { injectMenuState } from '@/layouts/use-menu-state';
import { useRoute } from 'vue-router';
import router from '@/router';
import { addRoute } from '@/router/generator-routers';

(function defineRouteApi(window) {
  window.addEventListener('message', (e) => {
    if (!e.data?.type) {
      return;
    }
    const actionType = e.data.type;
    if (actionType === 'addTab') {
      if (!e.data.param) {
        throw new Error('缺少添加新页签参数:param <{ path, route?, url? }>');
      }
      const { route, url, path } = e.data.param;
      if (route) {
        addRoute({ route, url });
      }
      router.push(path);
    }
  });
})(window);
export default defineComponent({
  name: 'MultiTab',
  components: {
    ReloadOutlined,
    EllipsisOutlined,
    CloseOutlined,
    DashbordDropdown: defineAsyncComponent(() => import('./dashbord-dropdown/index_top.vue'))
  },
  inheritAttrs: false,
  props: {
    fixed: {
      type: Boolean,
      default: () => false
    },
    defaultHomePage: {
      type: String,
      default: () => '/dashboard/analysis'
    }
  },
  setup(props) {
    const menuState = injectMenuState();
    const store = injectMultiTabStore();
    const cacheListLength = computed(() => store?.cacheList.length || 0);
    const route = useRoute();
    const activeKey = computed(() => menuState.selectedKeys && menuState.selectedKeys.value[menuState.selectedKeys.value.length - 1]);
    const isMobile = inject('isMobile', ref(false));
    const sideWidth = computed(
      () =>
        (menuState.sideWidth &&
          menuState.sideWidth.value &&
          !isMobile.value &&
          props.fixed &&
          `calc(100% - ${menuState.sideWidth.value}px)`) ||
        '100%'
    );
    const { t } = useI18n();
    const spin = ref(false);
    const [{ refresh, close, closeLeft, closeRight, closeOther, fullScreen, exitFullScreen }] =
      useMultiTab(/* { defaultHomePage: props.defaultHomePage } */);

    const handleActiveKeyChange = (key: string) => {
      menuState.selectedKeys!.value = [key];
    };
    const handleReloadPage = async (key?: string) => {
      spin.value = true;
      await refresh(key);
      spin.value = false;
    };

    const handleClose = (e: Event, target: string) => {
      close(target);
      e.stopPropagation();
    };

    return {
      t,
      activeKey,
      handleActiveKeyChange,
      handleReloadPage,
      closeLeft,
      closeRight,
      closeOther,
      handleClose,
      spin,
      sideWidth,
      cacheListLength,
      route,
      store,
      fullScreen,
      exitFullScreen
    };
  }
});
</script>

<style lang="less" scoped>
@import '../base-layouts/basic-layout.less';

// @multi-tab-height: 62px;
.ant-pro-multi-tab-wrap {
  background: @component-background;
}
.ant-pro-multi-tab-wrap :deep(.ant-tabs-nav) {
  padding-left: 8px;
  height: 34px;

  .ant-tabs-tab {
    padding: 0;
    border-radius: 4px 4px 0 0;
    border-color: #e5e6eb;
    background-color: #f7f8fa;
    transition: none;
    & > div {
      display: flex;
    }
    /* 创建内阴影 */
    &:first-child {
      &.ant-tabs-tab-active {
        background: #ffffff;
        border-bottom-color: #ffffff;
      }
    }
    &.ant-tabs-tab-active {
      background: #ffffff;
      border-bottom-color: #ffffff;
      // box-shadow: inset 0px 1px 1px 0px rgba(0, 0, 0, 0.04);
      .ant-pro-multi-tab-title {
        color: @primary-color;
      }
      // &::before {
      //   content: '';
      //   position: absolute;
      //   top: initial;
      //   display: block;
      //   bottom: -1px;
      //   left: -4px;
      //   height: 4px;
      //   width: 4px;
      //   z-index: 2;
      //   border: 0;
      //   border-radius: 0;
      //   background-color: #dbeafe;
      //   clip-path: path('M 4,0 C 4,0 4,4 0,4 L 4,4 Z');
      //   transition: none;
      // }

      // &::after {
      //   content: '';
      //   position: absolute;
      //   bottom: -1px;
      //   right: -4px;
      //   height: 4px;
      //   width: 4px;
      //   z-index: 2;
      //   background-color: #dbeafe;
      //   clip-path: path('M 0,0 C 0,0 0,4 4,4 L 0, 4 Z');
      // }
    }
    .ant-pro-multi-tab-reload-btn {
      margin-right: 0;
      margin-left: 8px;
      color: @text-color-secondary;
      font-size: @font-size-sm;
      vertical-align: -0.05em;
      &:hover {
        color: @primary-color;
      }
    }
    .ant-pro-multi-tab-close-btn {
      margin-right: 0;
      margin-left: 8px;
      color: @text-color-secondary;
      font-size: 12px;
    }
  }
  .ant-pro-multi-tab-title {
    display: flex;
    align-items: center;
    padding: 0 12px;
    color: @text-color-secondary;
    .ant-pro-multi-tab-title-text {
      display: block;
      max-width: 200px;
      overflow: hidden;
      text-overflow: ellipsis;
      white-space: nowrap;
    }
  }
}
.ant-pro-multi-tab-fixed {
  width: 100%;
  background: transparent;
}
.ant-pro-multi-tab-wrap-fixed {
  position: fixed;
  top: @pro-layout-header-height;
  right: 0;
  z-index: 8;
  width: 100%;
  transition: width 0.2s;
}
.ant-pro-multi-tab-dropdown-menu-btn {
  margin-right: 8px;
  padding: 10px;
  font-size: 16px;
  cursor: pointer;
  &:hover {
    color: @primary-color;
  }
}
</style>
